package com.dgut.dao;

import com.dgut.domain.User;

import java.sql.*;

public class JDBCDemo {

    public void findAllUsers() throws SQLException, ClassNotFoundException {
        //加载数据库驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //1.获取数据库连接
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis", "root", "xieman123");
        //2.创建数据库句柄，参数是我们要执行的sql语句
        PreparedStatement statement = connection.prepareStatement("select * from user");
        //3.执行查询操作，返回结果集
        ResultSet rs = statement.executeQuery();
        //4.遍历我们的结果集
        while (rs.next()){
            //获取结果集里面的属性
            int id = rs.getInt("id");
            String name = rs.getString(2);
            User user = new User();
            user.setUsername(name);
            user.setId(id);
            System.out.println(user);
        }
        //5.关闭资源
        rs.close();
        statement.close();
        connection.close();
    }

    public void findUserByUsername(String username) throws SQLException {
        //1.获取数据库连接
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis", "root", "xieman123");
        //2.创建数据库句柄，参数是我们要执行的sql语句
        PreparedStatement statement = connection.prepareStatement("select * from user where username = ?");
        statement.setString(1,username);
        //3.执行查询操作，返回结果集
        ResultSet rs = statement.executeQuery();
        //4.遍历我们的结果集
        while (rs.next()){
            //获取结果集里面的属性
            int id = rs.getInt("id");
            String name = rs.getString(2);
            User user = new User();
            user.setUsername(name);
            user.setId(id);
            System.out.println(user);
        }
        //5.关闭资源
        rs.close();
        statement.close();
        connection.close();
    }


    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        JDBCDemo demo = new JDBCDemo();
        demo.findAllUsers();
//        demo.findUserByUsername("xieman");
    }
}
